using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using BlogEngine.Core;

namespace BlogEngine.Core.Providers
{
  /// <summary>
  /// Microsoft SQL Server Implementation of BlogProvider
  /// </summary>
    public partial class MSSQLBlogProvider : BlogProviderBase
    {
        private string _DatabaseName = "BlogEngine";

        /// <summary>
        /// Initializes the provider
        /// </summary>
        /// <param name="name">Configuration name</param>
        /// <param name="config">Configuration settings</param>
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (String.IsNullOrEmpty(name))
            {
                name = "MSSQLBlogProvider";
            }

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "MSSQL Blog Provider");
            }

            base.Initialize(name, config);

            if (!string.IsNullOrEmpty(config["connectionStringName"]))
            {
                _DatabaseName = config["connectionStringName"];
            }

            config.Remove("connectionStringName");
        }


		/// <summary>
		/// Gets the guids.
		/// </summary>
		/// <param name="query">The query.</param>
		/// <returns></returns>
		public List<Guid> GetGuids(string query)
		{
			List<Guid> guids = new List<Guid>();

			SQLManagedConnection myConn = SQLManagedConnection.GetConnection(_DatabaseName);

			try
			{
				myConn.GetTextCommand(query);

				using (IDataReader rdr = myConn.ExecuteReader())
				{
					while (rdr.Read())
						guids.Add(rdr.GetGuid(0));

					rdr.Close();
				}
			}
			finally
			{
				myConn.CloseIfNonTransactional();
			}

			return guids;
		}
    }
}
